<?php
declare (strict_types = 1);

namespace app\command;

use app\common\models\Community\Villages;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class China extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('china')
            ->setDescription('the china command');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始时间:'.date('Y-m-d H:i:s'));
        $province = Db::name('china_provinces')->where('code',65)->select();
        foreach ($province as $p){
            $city = Db::name('china_cities')->where('provinceCode',$p['code'])->select();
            foreach($city as $c){
                $area = Db::name('china_areas')->where('cityCode',$c['code'])->select();
                foreach($area as $a){
                    $street = Db::name('china_streets')->where('areaCode',$a['code'])->select();
                    foreach($street as $s){
                        $village = Db::name('china_villages')->where('streetCode',$s['code'])->select();
                        $data = [];
                        foreach ($village as $v){
                            dump($p['code'].$p['name'].$c['code'].$c['name'].$a['code'].$a['name'].$s['code'].$s['name'].$v['code'].$v['name']);
                            $community = Db::name('community')->where('comm_id',$v['code'])->find();
                            if($community){
                                Db::name('community')->where('comm_id',$v['code'])->update(['street_id' => $s['code']]);
                                continue;
                            }
                            $data[] = [
                                'name' => $v['name'],
                                'province' => $p['name'],
                                'province_id' => $p['code'],
                                'city' => $c['name'],
                                'city_id' => $c['code'],
                                'country' => $a['name'],
                                'country_id' => $a['code'],
                                'street' => $s['name'],
                                'street_id' => $s['code'],
                                'comm' => $v['name'],
                                'comm_id' => $v['code'],
                            ];
                        }
                        try{
                            if(!empty($data)){
                                Db::name('community')->insertAll($data);
                            }
                        }catch (\Exception $e){
                            $output->writeln($e->getMessage());
                        }

                    }
                }
            }

        }
        // 指令输出
        $output->writeln('结束时间:'.date('Y-m-d H:i:s'));
    }
}
